import socket
import threading
from datetime import datetime

class BrainSignalReceiver:
    def __init__(self, host='127.0.0.1', port=8888):
        self.host = host
        self.port = port
        self.server_socket = None
        self.client_connection = None
        self.client_address = None
        self.running = False
        
    def start_server(self):
        """启动接收服务器"""
        try:
            self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.server_socket.bind((self.host, self.port))
            self.server_socket.listen(1)  # 只接受一个客户端连接
            
            print(f"脑机信号接收器已启动在 {self.host}:{self.port}")
            print("等待发送端连接...")
            
            self.running = True
            
            # 接受客户端连接的线程
            accept_thread = threading.Thread(target=self.accept_connection)
            accept_thread.daemon = True
            accept_thread.start()
            
            # 等待用户输入停止服务器
            input("按回车键停止服务器...\n")
            
        except Exception as e:
            print(f"启动服务器失败: {e}")
        finally:
            self.stop_server()
    
    def accept_connection(self):
        """接受客户端连接"""
        try:
            self.client_connection, self.client_address = self.server_socket.accept()
            print(f"发送端已连接: {self.client_address}")
            
            # 开始接收数据的线程
            receive_thread = threading.Thread(target=self.receive_data)
            receive_thread.daemon = True
            receive_thread.start()
            
        except Exception as e:
            if self.running:
                print(f"接受连接时发生错误: {e}")
    
    def receive_data(self):
        """接收数据并转发到处理端"""
        buffer = ""
        
        # 连接到处理端
        try:
            process_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            process_socket.connect(('127.0.0.1', 8889))  # 连接到处理端
            print("已连接到处理端")
        except Exception as e:
            print(f"无法连接到处理端: {e}")
            return
        
        while self.running and self.client_connection:
            try:
                data = self.client_connection.recv(1024).decode('utf-8')
                if not data:
                    print("发送端连接已断开")
                    break
                    
                buffer += data
                # 处理完整指令（假设以换行符分隔）
                while '\n' in buffer:
                    line, buffer = buffer.split('\n', 1)
                    signal = line.strip()
                    timestamp = datetime.now().strftime("%H:%M:%S.%f")[:-3]
                    print(f"[{timestamp}] 接收: {signal}")
                    
                    # 转发到处理端
                    try:
                        process_socket.sendall(f"{signal}\n".encode('utf-8'))
                    except Exception as e:
                        print(f"转发到处理端失败: {e}")
                        break
                        
            except Exception as e:
                print(f"接收数据错误: {e}")
                break
        
        # 关闭处理端连接
        try:
            process_socket.close()
        except:
            pass

    def stop_server(self):
        """停止服务器"""
        self.running = False
        if self.server_socket:
            self.server_socket.close()
        if self.client_connection:
            self.client_connection.close()
        print("接收服务器已停止")

if __name__ == "__main__":
    receiver = BrainSignalReceiver()
    receiver.start_server()